﻿using qqdest.DAO;
using qqdest.Model;
using qqdest.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace qqdest.DaoImpl
{


    internal class UserDaoImpl : IUserDao
    {
        // 使用 List 来代替数据库当中的数据, 并在构造函数当中完成初始化
        private static List<User> users = null;


        public UserDaoImpl()
        {
            // 初始化集合并向里面添加一个管理员账号
            if(null == users)
            {
                users = new List<User>();
                users.Add(new User() { username = "admin1", password = "123456", phonenumber = "13277427309", nickname = "管理员" });
            }
        }

        public User findUserByUserName(string userName)
        {
            foreach (var user in users)
            {
                if(user.username == userName) return user;
            }
            return null;
        }

        public User findUserByPhoneNumber(string phoneNumber)
        {
            foreach (var user in users)
            {
                if (user.phonenumber == phoneNumber) return user;
            }
            return null;
        }

        public User findUserById(string id)
        {
            foreach (var user in users)
            {
                if (user.Id == id) return user;
            }
            return null;
        }

        public bool InsertUser(User user)
        {
            // 判断是否存在用户名相同的 User
            foreach (var userItem in users)
            {
                if (userItem.username == user.username)
                {
                    return false;
                }
            }

            // 生成ID
            do
            {
                string id = RandomUtil.GenerateRandomDigits(10);
                User userByUsername = findUserById(id);
                if (userByUsername == null)
                {
                    user.Id = id;
                    break;
                }
            } while (true);

            // 插入数据库
            users.Add(user);

            return true;
        }

    }
}
